#!/usr/bin/env node

//Routes File

'use strict'

/* MODULE IMPORTS */
const Router = require('koa-router');
const koaBody = require('koa-body')({multipart: true, uploadDir: '.'});
const userSession = require('../lib/userSessionUnit');
//const jimp = require('jimp')

/* IMPORT CUSTOM MODULES */
const User = require('../modules/user');

const router = new Router();

/**
 * The user registration page.
 *
 * @name Register Page
 * @route {GET} /register
 */
router.get('/register', async ctx => await ctx.render('register'))

/**
 * The script to process new user registrations.
 *
 * @name Register Script
 * @route {POST} /register
 */
router.post('/register', async ctx => {
	try {
		// extract the data from the request
		const body = ctx.request.body;
		
		// call the functions in the module
		const user = await new User();
	  await user.register(body.user, body.pass, body.email, body.avatar);
		// await user.uploadPicture(path, type);
		// redirect to the home page
		ctx.redirect(`/login?msg=new user "${body.user}" added`)
	} catch(err) {
		await ctx.render('error', {message: err.message})
	}
})

router.get('/login', async ctx => {
	const data = {}
	if(ctx.query.msg) data.msg = ctx.query.msg
	if(ctx.query.user) data.user = ctx.query.user
	await ctx.render('login', data)
})

router.post('/login', async ctx => {
	try {
		const body = ctx.request.body;

		const user = await new User();
		let userData = await user.login(body.user, body.pass);

		userSession.login(ctx, userData);
		return ctx.redirect('/main')
	} catch(err) {
		await ctx.render('error', {message: err.message})
	}
})

router.get('/logout', async ctx => {
	userSession.logout(ctx);
	ctx.redirect('/?msg=you are now logged out')
})

module.exports = router;

